<?php

class AssetCache extends CFilterWidget {
	
	public $beginning = false;
	
	public function init() {
		ob_start();
		ob_implicit_flush(false);
	}
	
	public function filter($filterChain) {
		if(!$this->beginning) {
			$this->beginning = true;
			$filterChain->run();
		}
		$this->run();
	}
	
	public function run() {
		$content = ob_get_clean();
		
		$patterns = array(
			'js' => array(
				'/<script.*?type\s?=\s?[\'|"]text\/javascript[\'|"].*?src\s?=\s?[\'|"](.*?)[\'|"]>\s?<\/script>/si'
			),
			'css' => array(
				'/<link.*?type\s?=\s?[\'|"]text\/css[\'|"].*?href\s?=\s?[\'|"](.*?)[\'|"] \/>/si'
			),
		);
		
		
		$basePath = dirname(Yii::app()->basePath);
		$baseUrlLen = strlen(Yii::app()->baseUrl);
		
		$newAssetHtml = '';
			
		foreach($patterns as $type=>$typePatterns) {
			$fileContents = '';
			foreach($typePatterns as $pattern) {
				if(preg_match_all($pattern, $content, $matches)) {
					foreach($matches[1] as $src) {
						$src = substr($src, $baseUrlLen);
						$filename = $basePath . $src;
						$fileContents .= file_get_contents($filename);
					}
					$outputFile = 'd:\\'.$type.'.'.$type;
					file_put_contents($outputFile, $fileContents);
					$url = Yii::app()->assetManager->publish($outputFile);
					$newAssetHtml .= $type=='js' 
						? CHtml::scriptFile($url)
						: CHtml::cssFile($url);
					$content = str_replace($matches[0], '', $content);
				}
			}
			
		}
		
			
		if($newAssetHtml) {
			$content = preg_replace('/<head>(.*?)<\/head>/is', '\1'.$newAssetHtml, $content);
		}
				
		
		echo $content;
	}
	
	
}

?>